package com.xinjian.jianba.controller;

import com.alibaba.fastjson.JSONObject;
import com.xinjian.jianba.dto.pay.AllProductDto;
import com.xinjian.jianba.dto.pay.ApplePayDto;
import com.xinjian.jianba.dto.pay.BuyGiftDto;
import com.xinjian.jianba.dto.pay.BuyMeetcoinDto;
import com.xinjian.jianba.dto.pay.GiftVo;
import com.xinjian.jianba.dto.pay.OrderIsPayDto;
import com.xinjian.jianba.dto.pay.PayResultVo;
import com.xinjian.jianba.dto.pay.ProductVo;
import com.xinjian.jianba.dto.pay.SendGiftDto;
import com.xinjian.jianba.dto.pay.SetPayPasswordDto;
import com.xinjian.jianba.dto.pay.UpdateOrderDto;
import com.xinjian.jianba.dto.pay.UserAccountDetailDto;
import com.xinjian.jianba.dto.pay.UserAccountDetailVo;
import com.xinjian.jianba.dto.pay.UserAccountInfoDto;
import com.xinjian.jianba.dto.pay.UserAccountInfoVo;
import com.xinjian.jianba.dto.pay.UserGiftDetailDto;
import com.xinjian.jianba.dto.pay.UserGiftVo;
import com.xinjian.jianba.exception.Page;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.service.PayService;
import com.xinjian.jianba.service.ValidatorService;
import com.xinjian.jianba.utils.JsonUtil;
import com.xinjian.jianba.utils.LogBuilder;
import com.xinjian.jianba.utils.ModuleEnum;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 支付控制器
 */
@RestController
@RequestMapping("/api/v3/jianba/pay")
public class PayController extends AbstractController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private PayService payService;

    @Autowired
    private ValidatorService validatorService;
    @Value("${jianba.phone.regex}")
    private String mobileRegex;

    /**
     * 个人账户见币数量
     *
     */
    @PostMapping(value = { "/userAccountInfo" })
    public String userAccountInfo(@RequestBody UserAccountInfoDto userAccountInfoDto) {
        LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "个人账户见币数量, userAccountInfoDto={}"), userAccountInfoDto);

        try {
            if (userAccountInfoDto.getUserId() == null) {
                return this.responseClientJsonData(ResponseCode.ERROR, "用户id不能为空！");
            }
            UserAccountInfoVo resultVo = payService.userAccountInfo(userAccountInfoDto.getUserId());
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, resultVo);
        } catch (Exception e) {
            LOGGER.error("------userAccountInfo--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, ResponseCode.ERROR_MSG);
        }
    }

    /**
     * 设置密码
     *
     */
    @PostMapping(value = { "/setPassword" })
    public String setPassword(@RequestBody SetPayPasswordDto bindMobileDto) {
        LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "设置支付密码, bindMobileDto={}"), JsonUtil.getJsonString(bindMobileDto));
        try {
            validatorService.valid(bindMobileDto);
            payService.setPassword(bindMobileDto);
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
        } catch (Exception e) {
            LOGGER.error("------bindMobile--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
        }
    }

    /**
     * 修改支付密码
     *
     */
    @PostMapping(value = { "/updatePassword" })
    public String updatePassword(@RequestBody SetPayPasswordDto bindMobileDto) {
        LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "修改支付密码, bindMobileDto={}"), JsonUtil.getJsonString(bindMobileDto));
        try {
            validatorService.valid(bindMobileDto);
            payService.updatePassword(bindMobileDto);
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
        } catch (Exception e) {
            LOGGER.error("------bindMobile--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
        }
    }

    /**
     * 用户收到的礼物列表
     */
    @PostMapping(value = { "/gift/list" })
    public String userGiftList(@RequestBody UserGiftDetailDto userGiftDetailDto) {
        try {
            LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "用户礼物账单收益,参数  userGiftDetailDto={}"),
                    JsonUtil.getJsonString(userGiftDetailDto));
            if (userGiftDetailDto.getReceiveUserId() == null) {
                return this.responseClientJsonData(ResponseCode.ERROR, "用户id不能为空！");
            }
            Page<UserGiftVo> resultPage = payService.userGiftList(userGiftDetailDto);
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, resultPage);
        } catch (Exception e) {
            LOGGER.error("------userGiftList--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
        }
    }

    /**
     * 用户账单明细
     */
    @PostMapping(value = { "/account/detail" })
    public String userAccountDetail(@RequestBody UserAccountDetailDto userAccountDetailDto) {
        try {
            LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "用户礼物账单收益,参数  userAccountDetailDto={}"),
                    JsonUtil.getJsonString(userAccountDetailDto));
            if (userAccountDetailDto.getUserId() == null) {
                return this.responseClientJsonData(ResponseCode.ERROR, "用户id不能为空！");
            }
            Page<UserAccountDetailVo> resultPage = payService.userAccountDetail(userAccountDetailDto);
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, resultPage);
        } catch (Exception e) {
            LOGGER.error("------userAccountDetail--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, ResponseCode.ERROR_MSG);
        }
    }

    /**
     * 送礼物
     */
    @PostMapping(value = { "/sendGift" })
    public String sendGift(@RequestBody BuyGiftDto buyGiftDto) {
        try {
            LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "送礼物,参数  buyGiftDto={}"), JsonUtil.getJsonString(buyGiftDto));

            validatorService.valid(buyGiftDto);
            SendGiftDto result = payService.sendGift(buyGiftDto);
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, result);
        } catch (Exception e) {
            LOGGER.error("------buyGift--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
        }
    }

    /**
     * 购买见币
     */
    @PostMapping(value = { "/buy/meetcoin" })
    public String buyMeetcoin(@RequestBody BuyMeetcoinDto buyMeetcoinDto) {
        try {
            LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "购买见币,参数  buyMeetcoinDto={}"),
                    JsonUtil.getJsonString(buyMeetcoinDto));

            validatorService.valid(buyMeetcoinDto);
            PayResultVo result = payService.buyMeetcoin(buyMeetcoinDto);
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, result);
        } catch (Exception e) {
            LOGGER.error("------buyMeetcoin--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
        }
    }

    /**
     * 支付平台异步通知
     */
    @RequestMapping(value = { "/notify/{payWayCode}" })
    @ResponseBody
    public void notifyPay(@PathVariable("payWayCode") String payWayCode, HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse) throws Exception {
        LOGGER.info("into notify,payWayCode:" + payWayCode);
        String printStr = null;
        try {
            printStr = payService.notifyPay(payWayCode, httpServletRequest);
        } catch (Exception e) {
            LOGGER.error("------buyMeetcoin--error--->>>>>", e);
            e.printStackTrace();
        }
        httpServletResponse.getWriter().print(printStr);
    }

    /**
     * 所有商品
     */
    @PostMapping(value = { "/getAllProduct" })
    public String getAllProduct(@RequestBody AllProductDto allProductDto) {
        try {
            if (allProductDto.getSourceType() == null) {
                return this.responseClientJsonData(ResponseCode.ERROR, "设备类型不能为空！");
            }

            List<ProductVo> resultList = payService.allProduct(allProductDto.getSourceType());
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, resultList);
        } catch (Exception e) {
            LOGGER.error("------getAllProduct--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, ResponseCode.ERROR_MSG);
        }
    }

    /**
     * 所有礼品
     */
    @PostMapping(value = { "/getAllGift" })
    public String getAllGift() {
        try {
            List<GiftVo> resultList = payService.allGift();
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, resultList);
        } catch (Exception e) {
            LOGGER.error("------getAllGift--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, ResponseCode.ERROR_MSG);
        }
    }

    @PostMapping(value = { "/applePay" })
    public String applePay(@RequestBody ApplePayDto applePayDto) {
        LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "iosKey,参数  applePay={}"), JsonUtil.getJsonString(applePayDto));
        try {
            validatorService.valid(applePayDto);
            JSONObject restult = payService.applePay(applePayDto);
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, restult);
        } catch (Exception e) {
            LOGGER.error("------applePay--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, ResponseCode.ERROR_MSG);
        }
    }

    @PostMapping(value = { "/orderIsPay" })
    public String orderIsPay(@RequestBody OrderIsPayDto orderIsPayDto) {
        LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "查询订单是否支付,参数  orderIsPayDto={}"),
                JsonUtil.getJsonString(orderIsPayDto));
        try {
            validatorService.valid(orderIsPayDto);
            Object restult = payService.orderIsPay(orderIsPayDto);
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG, restult);
        } catch (Exception e) {
            LOGGER.error("------orderIsPay--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, ResponseCode.ERROR_MSG);
        }
    }

    @PostMapping(value = { "/updateOrder" })
    public String updateOrder(@RequestBody UpdateOrderDto updateOrderDto) {
        LOGGER.info(LogBuilder.build(ModuleEnum.PAY, "修改订单,参数  updateOrderDto={}"),
                JsonUtil.getJsonString(updateOrderDto));
        try {
            validatorService.valid(updateOrderDto);
            payService.updateOrder(updateOrderDto.getOrderNo());
            return this.responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
        } catch (Exception e) {
            LOGGER.error("------updateOrder--error--->>>>>", e);
            return this.responseClientJsonData(ResponseCode.ERROR, ResponseCode.ERROR_MSG);
        }
    }
}
